<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>我的流水</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="/common/plugins/element-plus/index.css" />
    <!-- Iconify 图标 -->
    <script src="/common/plugins/iconify/iconify-icon.min.js"></script>
    <!-- Tailwind CSS -->
    <script src="/common/plugins/tailwindcss/tailwind.min.js"></script>
    <script src="/common/plugins/vue/vue.global.js"></script>
    <script src="/common/plugins/element-plus/index.full.js"></script>
    <script src="/common/plugins/axios/axios.min.js"></script>
    <script src="/common/js/axios-config.js"></script>
    <style>
        [v-cloak] {
            display: none;
        }

        body {
            margin: 0;
            padding: 16px;
            background-color: #f5f5f5;
        }
    </style>
</head>

<body class="bg-gray-50">
    <div id="app">
        <div id="page-management__my-transactions" v-cloak>
            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
                <el-card>
                    <div class="flex items-center justify-between p-2">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <iconify-icon icon="mdi:account-cash" width="40" height="40" class="text-green-500"></iconify-icon>
                            </div>
                            <div class="ml-4">
                                <p class="text-sm text-gray-600">当前余额</p>
                                <p class="text-2xl font-bold text-green-600">¥{{ userInfo.balance || 0 }}</p>
                            </div>
                        </div>
                        <div class="ml-6">
                            <el-button type="primary" @click="showRechargeDialog = true" round>
                                <iconify-icon icon="mdi:wallet-plus" width="16" height="16" class="mr-1"></iconify-icon>
                                充值
                            </el-button>
                        </div>
                    </div>
                </el-card>

                <el-card>
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <iconify-icon icon="mdi:cash-plus" width="40" height="40"
                                class="text-blue-500"></iconify-icon>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-600">累计充值</p>
                            <p class="text-2xl font-bold text-blue-600">¥{{ statistics.totalRecharge || 0 }}</p>
                        </div>
                    </div>
                </el-card>
                <el-card>
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <iconify-icon icon="mdi:cash-minus" width="40" height="40"
                                class="text-red-500"></iconify-icon>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-600">累计消费</p>
                            <p class="text-2xl font-bold text-red-600">¥{{ statistics.totalConsumption || 0 }}</p>
                        </div>
                    </div>
                </el-card>
                <el-card>
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <iconify-icon icon="mdi:format-list-bulleted" width="40" height="40"
                                class="text-purple-500"></iconify-icon>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-600">流水记录</p>
                            <p class="text-2xl font-bold text-purple-600">{{ statistics.totalTransactions || 0 }}</p>
                        </div>
                    </div>
                </el-card>
            </div>

            <!-- 查询区域 -->
            <div class="p-4 bg-white rounded-lg shadow mb-3">
                <div class="flex items-center justify-between mb-2">
                    <h3 class="text-lg font-medium">查询条件</h3>
                </div>
                <el-form :inline="true">
                    <el-form-item label="流水类型">
                        <el-select v-model="searchParams.type" placeholder="请选择类型" clearable style="width: 178px;">
                            <el-option label="充值" :value="1"></el-option>
                            <el-option label="课程消费" :value="2"></el-option>
                            <el-option label="课程退款" :value="3"></el-option>
                            <el-option label="比赛报名费" :value="4"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="金额范围">
                        <el-input-number v-model="searchParams.minAmount" placeholder="最小金额" :precision="2"
                            style="width: 85px;"></el-input-number>
                        <span class="mx-2">-</span>
                        <el-input-number v-model="searchParams.maxAmount" placeholder="最大金额" :precision="2"
                            style="width: 85px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="交易日期">
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                            style="width: 240px;"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <iconify-icon icon="mdi:magnify" width="16" height="16" class="mr-1"></iconify-icon>搜索
                        </el-button>
                        <el-button @click="handleReset">
                            <iconify-icon icon="mdi:refresh" width="16" height="16" class="mr-1"></iconify-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 流水记录列表 -->
            <div class="bg-white rounded-lg shadow p-4 mb-5">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-lg font-medium">流水记录</h3>
                    <el-button size="small" @click="loadMyTransactions">
                        <iconify-icon icon="mdi:refresh" width="16" height="16" class="mr-1"></iconify-icon>刷新
                    </el-button>
                </div>
                <el-table :data="tableData" :border="true" v-loading="loading" style="width: 100%" empty-text="暂无流水数据"
                    class="w-full">
                    <el-table-column prop="id" label="流水号" width="100"></el-table-column>
                    <el-table-column prop="type" label="类型" width="120">
                        <template #default="scope">
                            <el-tag v-if="scope.row.type === 1" type="success" size="small">充值</el-tag>
                            <el-tag v-else-if="scope.row.type === 2" type="warning" size="small">课程消费</el-tag>
                            <el-tag v-else-if="scope.row.type === 3" type="info" size="small">课程退款</el-tag>
                            <el-tag v-else-if="scope.row.type === 4" type="danger" size="small">比赛报名费</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额" width="120">
                        <template #default="scope">
                            <span v-if="scope.row.amount > 0" class="text-green-600 font-semibold">+¥{{ scope.row.amount
                                }}</span>
                            <span v-else class="text-red-600 font-semibold">¥{{ scope.row.amount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="balanceAfter" label="余额变动后" width="120">
                        <template #default="scope">
                            <span class="text-blue-600 font-medium">¥{{ scope.row.balanceAfter || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="notes" label="备注">
                        <template #default="scope">
                            <span>{{ scope.row.notes || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="transactionTime" label="交易时间" width="180"></el-table-column>
                    <el-table-column label="操作" width="100" fixed="right">
                        <template #default="scope">
                            <el-button size="small" link type="primary" @click="handleViewDetail(scope.row)">
                                <iconify-icon icon="mdi:eye" width="16" height="16" class="mr-1"></iconify-icon>详情
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <div class="mt-5 flex justify-end">
                    <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"></el-pagination>
                </div>
            </div>

            <!-- 流水详情对话框 -->
            <el-dialog title="流水详情" v-model="detailDialogVisible" width="600px">
                <el-descriptions :column="2" border v-if="currentTransaction">
                    <el-descriptions-item label="流水号">{{ currentTransaction.id }}</el-descriptions-item>
                    <el-descriptions-item label="流水类型">
                        <el-tag v-if="currentTransaction.type === 1" type="success" size="small">充值</el-tag>
                        <el-tag v-else-if="currentTransaction.type === 2" type="warning" size="small">课程消费</el-tag>
                        <el-tag v-else-if="currentTransaction.type === 3" type="info" size="small">课程退款</el-tag>
                        <el-tag v-else-if="currentTransaction.type === 4" type="danger" size="small">比赛报名费</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="交易金额">
                        <span v-if="currentTransaction.amount > 0" class="text-green-600 font-semibold">+¥{{
                            currentTransaction.amount }}</span>
                        <span v-else class="text-red-600 font-semibold">¥{{ currentTransaction.amount }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="余额变动后">
                        <span class="text-blue-600 font-medium">¥{{ currentTransaction.balanceAfter || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="交易时间" :span="2">{{ currentTransaction.transactionTime
                        }}</el-descriptions-item>
                    <el-descriptions-item label="备注说明" :span="2">
                        <div class="whitespace-pre-wrap">{{ currentTransaction.notes || '无' }}</div>
                    </el-descriptions-item>
                    <el-descriptions-item label="关联信息" :span="2" v-if="currentTransaction.relatedInfo">
                        <div class="text-sm text-gray-600">
                            <p v-if="currentTransaction.type === 2 && currentTransaction.relatedInfo.coach">
                                <strong>课程教练：</strong>{{ currentTransaction.relatedInfo.coach }}
                            </p>
                            <p v-if="currentTransaction.type === 2 && currentTransaction.relatedInfo.courseTime">
                                <strong>课程时间：</strong>{{ currentTransaction.relatedInfo.courseTime }}
                            </p>
                            <p v-if="currentTransaction.type === 4 && currentTransaction.relatedInfo.competition">
                                <strong>比赛名称：</strong>{{ currentTransaction.relatedInfo.competition }}
                            </p>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </el-dialog>


            <!-- 充值弹窗 -->
            <el-dialog v-model="showRechargeDialog" title="账户充值" width="450px" :before-close="handleCloseRecharge">
                <div class="space-y-4">
                    <!-- 充值金额选择 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择充值金额</label>
                        <div class="grid grid-cols-3 gap-2 mb-3">
                            <el-button
                                    v-for="amount in quickAmounts"
                                    :key="amount"
                                    :type="rechargeAmount === amount ? 'primary' : 'default'"
                                    @click="rechargeAmount = amount"
                                    class="h-12">
                                ¥{{ amount }}
                            </el-button>
                        </div>
                        <el-input
                                v-model="rechargeAmount"
                                placeholder="或输入自定义金额"
                                type="number"
                                :min="10"
                                :max="10000">
                            <template #prepend>¥</template>
                        </el-input>
                        <p class="text-xs text-gray-500 mt-1">单次充值金额：10-10000元</p>
                    </div>

                    <!-- 支付说明 -->
                    <div class="bg-blue-50 p-3 rounded">
                        <p class="text-sm text-blue-600">
                            <iconify-icon icon="mdi:information" class="mr-1"></iconify-icon>
                            点击"确认充值"后将显示收款码，请扫码支付
                        </p>
                    </div>
                </div>

                <template #footer>
        <span class="dialog-footer">
            <el-button @click="showRechargeDialog = false">取消</el-button>
            <el-button type="primary" @click="showPaymentQR" :disabled="!rechargeAmount || rechargeAmount < 10">
                确认充值 ¥{{ rechargeAmount || 0 }}
            </el-button>
        </span>
                </template>
            </el-dialog>
             支付二维码弹窗
            <el-dialog v-model="showPaymentDialog" title="扫码支付" width="400px" :before-close="handleClosePayment">
                <div class="text-center space-y-4">
                    <div class="text-lg font-medium text-gray-800">
                        账户充值
                    </div>
                    <div class="text-2xl font-bold text-orange-500">
                        ¥{{ rechargeAmount }}
                    </div>

                    <!-- 收款码展示区 -->
                    <div class="flex justify-center my-6">
                        <div class="w-64 h-64 border-2 border-gray-200 rounded-lg overflow-hidden">
                            <img src="/images/payment-qr.jpg" alt="支付二维码" class="w-full h-full object-contain">
                        </div>
                    </div>

                    <div class="text-sm text-gray-600 space-y-1">
                        <p>请使用微信或支付宝扫描上方二维码</p>
                        <p>支付金额：<span class="font-medium text-orange-500">¥{{ rechargeAmount }}</span></p>
                        <p class="text-xs text-gray-500">支付完成后请点击"我已支付"按钮</p>
                    </div>
                </div>

                <template #footer>
                    <div class="flex justify-center space-x-3">
                        <el-button @click="handleClosePayment">取消支付</el-button>
                        <el-button type="primary" @click="confirmRecharge">
                            <iconify-icon icon="mdi:check-circle" width="16" height="16" class="mr-1"></iconify-icon>
                            我已支付
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted } = Vue;

        const app = createApp({
            data() {
                return {
                    // 查询参数
                    searchParams: {
                        type: undefined,
                        minAmount: undefined,
                        maxAmount: undefined
                    },
                    dateRange: [],
                    // 表格数据
                    tableData: [],
                    loading: false,
                    // 分页参数
                    pagination: {
                        pageNum: 1,
                        pageSize: 10,
                        total: 0
                    },
                    // 用户信息和统计数据
                    userInfo: {},
                    statistics: {
                        totalRecharge: 0,
                        totalConsumption: 0,
                        totalTransactions: 0
                    },
                    // 对话框
                    detailDialogVisible: false,
                    currentTransaction: null,
                    // 充值相关
                    showRechargeDialog: false,
                    showPaymentDialog: false,
                    rechargeAmount: null,
                    quickAmounts: [50, 100, 200, 500, 1000, 2000]
                };
            },

            methods: {
                // 加载我的流水记录
                async loadMyTransactions() {
                    this.loading = true;
                    try {
                        const params = { ...this.searchParams };

                        // 处理日期范围
                        if (this.dateRange && this.dateRange.length === 2) {
                            params.startDate = this.dateRange[0];
                            params.endDate = this.dateRange[1];
                        }

                        const response = await apiClient.post('/transactions/my-transactions', {
                            pageNum: this.pagination.pageNum,
                            pageSize: this.pagination.pageSize,
                            params: params
                        });

                        if (response.code === 200) {
                            this.tableData = response.data.list || [];
                            this.pagination.total = response.data.total || 0;
                        } else {
                            this.$message.error(response.message || '获取流水记录失败');
                        }
                    } catch (error) {
                        console.error('获取流水记录失败:', error);
                        this.$message.error('获取流水记录失败');
                    } finally {
                        this.loading = false;
                    }
                },

                // 加载用户信息和统计数据
                async loadUserInfoAndStats() {
                    try {
                        // 获取当前用户信息
                        const userInfo = getCurrentUserInfo();
                        if (userInfo) {
                            this.userInfo = userInfo;
                        }

                        // 获取统计数据
                        const response = await apiClient.get('/transactions/my-statistics');
                        if (response.code === 200) {
                            const data = response.data || {};
                            this.statistics = {
                                totalRecharge: data.totalRecharge || 0,
                                totalConsumption: data.totalConsumption || 0,
                                totalTransactions: data.totalTransactions || 0
                            };
                            // 更新用户余额信息
                            if (data.currentBalance !== undefined) {
                                this.userInfo.balance = data.currentBalance;
                            }
                        }
                    } catch (error) {
                        console.error('获取统计数据失败:', error);
                    }
                },

                // 查看详情
                handleViewDetail(row) {
                    this.currentTransaction = row;
                    this.detailDialogVisible = true;
                },

                // 查询
                handleSearch() {
                    this.pagination.pageNum = 1;
                    this.loadMyTransactions();
                },

                // 重置
                handleReset() {
                    this.searchParams = {
                        type: undefined,
                        minAmount: undefined,
                        maxAmount: undefined
                    };
                    this.dateRange = [];
                    this.pagination.pageNum = 1;
                    this.loadMyTransactions();
                },

                // 分页大小变化
                handleSizeChange(val) {
                    this.pagination.pageSize = val;
                    this.pagination.pageNum = 1;
                    this.loadMyTransactions();
                },

                // 当前页变化
                handleCurrentChange(val) {
                    this.pagination.pageNum = val;
                    this.loadMyTransactions();
                },
                // 显示支付二维码
                showPaymentQR() {
                    if (!this.rechargeAmount || this.rechargeAmount < 10 || this.rechargeAmount > 10000) {
                        this.$message.error('请输入有效的充值金额（10-10000元）');
                        return;
                    }

                    this.showRechargeDialog = false;
                    this.showPaymentDialog = true;
                },

                // 确认充值
                async confirmRecharge() {
                    try {
                        // 调用后端充值接口
                        const response = await apiClient.post('/transactions/recharge', null, {
                            params: {
                                amount: this.rechargeAmount,
                                paymentMethod: '扫码支付'
                            }
                        });

                        if (response.code === 200) {
                            this.$message.success(`充值成功！已充值 ¥${this.rechargeAmount}`);
                            // 刷新用户信息和流水列表
                            this.loadUserInfo();
                            this.loadMyTransactions();

                            this.handleClosePayment();
                        } else {
                            // this.$message.error(response.message || '充值失败');
                        }
                    } catch (error) {
                        console.error('充值失败:', error);
                        // this.$message.error('充值失败，请重试');
                    }
                },

                // 关闭充值弹窗
                handleCloseRecharge() {
                    this.showRechargeDialog = false;
                    this.rechargeAmount = null;
                },

                // 关闭支付弹窗
                handleClosePayment() {
                    this.showPaymentDialog = false;
                    this.rechargeAmount = null;
                }
            },

            async mounted() {
                await Promise.all([
                    this.loadUserInfoAndStats(),
                    this.loadMyTransactions()
                ]);
            }
        });

        app.use(ElementPlus);
        app.mount("#page-management__my-transactions");
    </script>
</body>

</html>